<template>
  <div :class="{'mt': isDetail}" class="link-form-content">
    <div class="top">
      <div style="flex-shrink: 0;"><Title :element="element" isTable /></div>
      <div v-if="(element.options.required || !!(requiredKeys && requiredKeys.includes(element.key))) && !isDetail" class="is-required">*</div>
      <template v-if="element.options && element.options.tip">
        <div v-if="element.options.tip.length < 20" class="tip">{{ element.options.tip }}</div>
        <ToolTip v-else :content="element.options.tip" class="tip" />
      </template>
      <div class="flex"/>
      <PlainCreateBtn v-if="!isDetail" @click="addForm">添加</PlainCreateBtn>
      <el-button v-if="!isDetail" size="small" class="delete-btn" @click="deleteItem">删除</el-button>
    </div>
    <div v-if="element.options && element.options.isStatistics && statistics.length" class="statistics-list">
      <dataDisplay
        :data-list="statistics"
        type="row"
        style="width:100%;"/>
    </div>
    <div>
      <el-table
        ref="linkTableRef"
        :data="handelTableData(listData)"
        :border="true"
        empty-text="暂无数据"
        fit
        element-loading-text="加载中..."
        header-cell-class-name="dynamic-edit-table-cell"
        @select="selectTable"
        @select-all="selectTable"
      >
        <EmptyPlaceholder slot="empty" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
        <el-table-column v-if="!isDetail" :key="element.key" :width="50" align="center" type="selection" />
        <el-table-column :width="50" align="left" label="序号" >
          <template slot-scope="scope">
            <div class="center">{{ scope.$index +1 }}</div>
          </template>
        </el-table-column>
        <template v-for="(colItem) in element.subform">
          <el-table-column v-if="colItem.key === 'status' && element.options.remoteParams.isCustom" :key="colItem.key" :label="colItem.name">
            <template slot-scope="scope">
              <StatusText
                :color="['#FFBC3D','#FD8546', '#FF4E5F', '#999', '#31CC9C','#406EFF'][scope.row.status]"
                :text="scope.row.status | processCommonStatus" />
            </template>
          </el-table-column>
          <!-- 链接 -->
          <el-table-column v-if="colItem.type === 'link' && element.options.remoteParams.isCustom" :key="colItem.key" :label="colItem.name">
            <template slot-scope="scope">
              <LinkElement
                v-if="scope.row.content && scope.row.content[colItem.key]"
                :link="scope.row.content[colItem.key]"
                :link-name="colItem.options.defaultLinkName" />
              <div v-else>--</div>
            </template>
          </el-table-column>
          <LinkFormTableColumn v-else :key="colItem.key + '-link'" :col-item="colItem" :element="element" :config-data="configData" />
        </template>
        <el-table-column align="left" label="操作" width="90" fixed="right">
          <template slot-scope="scope">
            <div class="button-text" @click="toDetail(scope.row)">查看</div>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-footer">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <span class="flex"/>
        <el-pagination
          v-if="(listData || []).length > 10"
          :page-sizes="[10, 20, 30, 50, 100, 250, 500]"
          :current-page="curPage"
          :page-size="perPage"
          :total="listData.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </div>
    <template v-if="element && element.options && element.options.remoteParams">
      <!-- 关联合同类 -->
      <RelatedContract v-if="isContractForm" ref="showRelatedContract" :form-make-element="element" :visible.sync="showRelatedContract" :has-contract-code="true" title="关联合同" @confirmRelatedContract="confirm" />
      <!-- 关联自定义表单 -->
      <RelatedLinkForm v-else-if="element.options.remoteParams.isCustom" ref="relatedLinkFormRef" :element="element" @confirm="confirm" />
      <!-- 关联其他审批 -->
      <RelatedProcess v-else ref="RelatedProcessRef" :element="element" :options="element.options.remoteParams" @confirm="confirm" />
    </template>
  </div>
</template>

<script>
// components
import Title from './Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import RelatedLinkForm from './relatedLinkForm';
import incomeAmount from '@/assets/dataDisplay/icon_45.png';
import RelatedContract from '@/components/CreateOrder/relatedContract';
import RelatedProcess from '@/components/Common/relatedProcess/index';
import LinkFormTableColumn from '@/components/Common/relatedProcess/LinkFormTableColumn';
import LinkElement from '@/views/legal/process/components/formMake/components/linkElement';
// mixins
import tableSelections from '@/mixins/tableSelections';
// tool
import ElMessage from '@/utils/message';
import { getConfigData } from '@/components/Common/relatedProcess/data';
import math from '@/utils/math';
import { processCommonStatus } from '@/filters/status';
import { isNumberType } from '@/utils/formMakeUtils.js';
// import options from '@/views/legal/module/options';

export default {
  components: { Title, EmptyPlaceholder, RelatedLinkForm, LinkElement,
    dataDisplay, RelatedContract, RelatedProcess, LinkFormTableColumn },
  filters: {
    processCommonStatus
  },
  mixins: [tableSelections],
  model: {
    prop: 'listData',
    event: 'changeData'
  },
  props: {
    listData: {
      type: Array,
      default: () => {
        return [{}];
      }
    },
    element: {
      type: Object,
      default: null
    },
    isDetail: { // 是否详情页展示
      type: Boolean,
      default: false
    },
    requiredKeys: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      curPage: 1,
      perPage: 10,
      idKey: 'id',
      tableRefName: 'linkTableRef',
      showRelatedContract: false
    };
  },
  computed: {
    statistics() {
      const listData = this.listData;
      const keys = [];
      if (this.element.options.remoteParams.isCustom) {
        this.element.subform.forEach(i => {
          if (isNumberType(i) || i.type === 'statistics') {
            const isShowPercentage = i.type === 'input' && i.options.isShowPercentage;
            keys.push({ data: null, label: i.name + '：', icon: incomeAmount, key: i.key, unit: isShowPercentage ? '%' : '', isShowPercentage });
          }
        });
      } else if (this.configData && this.configData.numberField) {
        this.configData.numberField.forEach(i => {
          const hasKey = this.element.subform.some(sub => sub.key === i.key);
          if (hasKey) keys.push({ data: null, label: i.name + '：', icon: incomeAmount, key: i.key, _unit: i.unit });
        });
      }
      keys.forEach(i => {
        let ans = null;
        listData.forEach(j => {
          let data = this.element.options.remoteParams.isCustom ? j.content[i.key] : j[i.key];
          if (data || data === 0) {
            if (i.isShowPercentage) {
              data = math.multiply(data, 100);
            }
            if (i._unit === '分') {
              ans = ans === null ? Number(data) / 100 : math.add(ans, Number(data) / 100);
            } else {
              ans = ans === null ? Number(data) : math.add(ans, Number(data));
            }
          }
        });
        i.data = ans;
      });
      return keys;
    },
    isContractForm() { // 是否合同类型的固定表单
      const options = this.element.options.remoteParams;
      if (options.isCustom || options.type !== 0) {
        return false;
      }
      return true;
    },
    configData() {
      if (!this.element || !this.element.options || !this.element.options.remoteParams) return null;
      const type = this.element.options.remoteParams.type;
      return getConfigData(type);
    }
  },
  methods: {
    /**
     * 跨页多选
     */
    handelTableData(tableData) {
      const pageData = tableData && tableData.slice((this.curPage - 1) * this.perPage, this.curPage * this.perPage) || [];
      this.setSelectRow && this.setSelectRow(pageData);
      return pageData;
    },
    handleSizeChange(val) {
      this.perPage = val;
    },
    handleCurrentChange(val) {
      this.curPage = val;
    },
    getBind(colItem) {
      let width = '';
      if (colItem.type === 'upAttachment') {
        width = 200;
      }
      return {
        align: 'left',
        minWidth: 120,
        width
      };
    },
    deleteItem() {
      const select = this.multipleSelectionAll || [];
      if (select.length === 0) {
        ElMessage.warning('请选择数据');
        return;
      }
      this.$confirm('请确认是否删除所选的数据', '', {
        confirmButtonText: '确定', type: 'warning',
        showClose: false, center: true, iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        const ids = select.map(i => i.id);
        const listData = this.listData.filter(i => {
          return !ids.includes(i.id);
        });
        this.clearMixinSelection();
        this.handleCurrentChange(1);
        this.$emit('changeData', listData);
      });
    },
    // 添加关联
    addForm() {
      if (this.isContractForm) {
        this.openSelectContract();
      } else if (this.element.options.remoteParams.isCustom) {
        this.$refs.relatedLinkFormRef.oepnDialog(this.listData);
      } else {
        this.$refs.RelatedProcessRef.oepnDialog(this.listData);
      }
    },
    openSelectContract() {
      this.showRelatedContract = true;
      this.$refs['showRelatedContract'].init();
      this.$refs['showRelatedContract'].initSelectData(this.listData || []);
    },
    confirm(listData) {
      this.$emit('changeData', listData);
      this.showRelatedContract = false;
    },
    toDetail(rowData) {
      const options = this.element.options.remoteParams;
      if (options.isCustom) {
        const moduleId = options.workFlowId || options.id;
        const routerParams = {
          name: 'approvalModuleDetail',
          params: { moduleId },
          query: { id: rowData.id, processId: rowData.processId }
        };
        const routeUrl = this.$router.resolve(routerParams);
        window.open(routeUrl.href, '_blank');
      } else {
        const configData = this.configData;
        let routerRedirect = null;
        if (configData && configData.fieldsProp) {
          for (const key in configData.fieldsProp) {
            if (configData.fieldsProp[key] && configData.fieldsProp[key].routerRedirect) {
              routerRedirect = configData.fieldsProp[key].routerRedirect;
              break;
            }
          }
        }
        if (routerRedirect) {
          const params = routerRedirect(rowData);
          const routeUrl = this.$router.resolve(params);
          window.open(routeUrl.href, '_blank');
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.link-form-content {
  background-color: #fff;
  &.mt {
    margin-top: 12px;
  }
  .top {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
  }
  .tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
  }
  .delete-btn {
    color: #666666;
    border-color: #ddd;
    background-color: #fff;
    padding: 7px 8px;
  }
  ::v-deep .el-table__empty-block {
    margin: 0 auto;
    min-height: 48px;
    height: 48px !important;
    .el-table__empty-text {
      line-height: 32px;
    }
  }
  &::v-deep {
    .cell-bg-box > .cell {
      height: 20px;
    }
    .text-bg {
      padding: 0 10px;
      border-radius: 999px;
      color: #fff;
      display: inline-block;
      height: 20px;
      line-height: 20px;
      max-width: 100%;
    }
  }
}
.statistics-list {margin-bottom: 12px;}
.flex {
  flex:1;
}
.table-footer {
  margin-top:12px; display:flex;
}
.is-required {
  color: #F56C6C;
  margin-left: 3px;
}
</style>
